﻿using crip.Common;
using crip.Database;
using crip.Models;
using crip.Services.IRepositorys;
using Microsoft.EntityFrameworkCore;

namespace crip.Services.Repositorys
{
    public class EventRepository: BaseRepository<Event>,IEventRepository
    {
        private readonly CripDbContext _cripDbContext;
        public EventRepository(CripDbContext cripDbContext):base(cripDbContext)
        {
            _cripDbContext = cripDbContext;
        }
        public async Task<bool> AddEventAsync(Event myevent)
        {
            if (myevent == null)
                return false;
            await _cripDbContext.Events.AddAsync(myevent);
            return true;
        }
        public async Task<PageList<Event>> GetEventsAsync(string?keyword, string? orderby, bool? desc, int pageNumber, int pageSize)
        {
            IQueryable<Event> res = _cripDbContext.Events
            .Include(x => x.Pictures);
            if(!String.IsNullOrEmpty(keyword))
            {
                keyword = keyword.Trim();
                var tmp1 = res.Where(x => x.EventName.Contains(keyword));
                var tmp2 = res.Where(x => x.EventDescription.Contains(keyword));
                res = tmp1.Union(tmp2);
            }
            res = orderby switch
            {
                "detail" => (desc == true) ? res.OrderByDescending(a => a.EventDetail) : res.OrderBy(a => a.EventDetail),
                "desrcription" => (desc == true) ? res.OrderByDescending(a => a.EventDescription) : res.OrderBy(a => a.EventDescription),
                "name" => (desc == true) ? res.OrderByDescending(a => a.EventName) : res.OrderBy(a => a.EventName),
                _ => (desc == true) ? res.OrderByDescending(a => a.StartTime) : res.OrderBy(a => a.StartTime)
            };
            return await PageList<Event>.CreateAsync(pageNumber, pageSize, res);
        }
        #region 删除用户的EventID通过 areaId
        public void DeleteEventsByAreaId(Guid areaId)
        {
            var deletingEvent = _cripDbContext.Events.Where(e => e.AreaId == areaId).ToList();
            DeleteEntitys(deletingEvent);
        }
        #endregion
        public async Task<Event> GetEventByEventIdAsync(Guid? guid)
        {
            return await _cripDbContext.Events.FirstAsync(a => a.Id == guid);
        }
        /*
        public  async Task CheckStatusAsync()
        {
            _cripDbContext.Events.ToList().ForEach(e =>
            {
                if (e.StartTime> DateTime.Now)
                {
                    e.ReadyToBegin();
                }
                else if (e.EndTime > DateTime.Now)
                {
                    e.ComingtoEnd();
                }

            });
            Console.WriteLine("成功");
        }
        */
    }
}
